ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Angular @input, @output & EventEmitter

In this guide let us learn how to make use of @input, @output & EventEmitter in Angular. We use these decorators to pass data from parent to child component & vice versa.@Input defines the input property in the component, which the parent component can set. The @output defines the output property (event), which we raise in the child component using the EventEmitter. The parent listens to these events.

@input, @output & Eventemitter

@input

Input decorator marks the property as the input property. I.e it can receive data from the parent component. The parent component uses the property binding to bind it to a component property. Whenever the value in the parent component changes angular updates the value in the child component.

Example

Consider the following component class

                              
 
@Component,({
  selector: 'app-customer-detail',
  templateUrl: './customer-detail.component.html',
  styleUrls: ['./customer-detail.component.css']
})
export class CustomerDetailComponent implements OnInit {
  @Input,() customer:Customer;
}
 
                            
                        

We have Input decorator on the customer property. The component expects that the parent component will supply its value.

The parent component supplies the customer object using the property binding syntax. We add a square bracket around the customer property. Assign template expression (selectedCustomer) to it, which is a property in the parent component.

                              
 
<app-customer-detail [customer]="selectedCustomer"></app-customer-detail>
                            
                        

@output

Output decorates the property as the output property. We initialize it as an EventEmitter. The child component raises the event and passes the data as the argument to the event. The parent component listens to events using event binding and reads the data.

                              
 
//Declare the property
@Output,() customerChange:EventEmitter<Customer> =new EventEmitter<Customer>();
 
//Raise the event to send the data back to parent
update() {
  this.customerChange.emit(this.customer);
}
 
                            
                        

The customerChange is the Output property and is of type EventEmitter.

In the parent component, we subscribe to the event using the event binding syntax. Use the () around the event name (customerChange) and assign a template statement (update($event)) to it. It receives the data in the $event argument.

                              
 
<app-customer-detail [customer]="selectedCustomer" (customerChange)="update($event)"></app-customer-detail>
 
                            
                        

Remember you must use the argument name as $event.

EventEmitter

EventEmitter is responsible for raising the event. The @output property normally is of type EventEmitter. The child component will use the emit() method to emit an event along with the data.

                              

//Define  output property
@Output,() customerChange:EventEmitter<Customer> =new EventEmitter<Customer>(); 
 
//Raise the event using the emit method.
update() {
  this.customerChange.emit(this.customer);
}
 
                            
                        

Now let us build an app to learn how to use Input, output & EventEmitter

@input, @output & Eventemitter Example

The app we build has two components. The parent component shows a list of customers. The user has the option to click on the edit button, which results in a child component displaying the customer form Once the user updates the records, the child component raises the event. The parent captures the event. The parent then updates the list with the new data.

Create a new application using the following command

                              

ng new InputOutputExample
 
 
cd InputOutputExample
 
                            
                        

Create the customerList & customerDetail components. Also, create the customer class

                              

ng g c customerList
ng g c customerDetail
ng g class customer
 
                            
                        
Customer
                              
 
export class Customer {
 
  customerNo: number=0;
  name: string="";
  address: string="";
  city: string="";
  state: string="";
  country: string="";
 
}
 
                            
                        

The ngModel needs the FormsModule. Hence import it and add it in import metadata.

app.module.ts
                              

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomerListComponent } from './customer-list/customer-list.component';
import { CustomerDetailComponent } from './customer-detail/customer-detail.component';
 
@NgModule({
  declarations: [
    AppComponent,
    CustomerListComponent,
    CustomerDetailComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule { }
 
 
                            
                        

Child Component

The child component gets an instance of the customer in its input property customer. The parent needs to set it using the property binding

Users can edit the customer. Once finished they will click the update button. The update method raises the customerChange event. We pass the customer as the argument to the event. The parent component listens to the event and receives the data.

The following is the complete code of the CustomerDetailComponent.

                              
 
import { Component, OnInit, Input, Output,EventEmitter } from '@angular/core';
import { Customer } from '../customer';
 
@Component,({
  selector: 'app-customer-detail',
  templateUrl: './customer-detail.component.html',
  styleUrls: ['./customer-detail.component.css']
})
export class CustomerDetailComponent implements OnInit {
 
  @Input,() customer:Customer = new Customer();
  @Output,() customerChange:EventEmitter<Customer> =new EventEmitter<Customer>(); 
    
  constructor() { }
 
  ngOnInit() {
  }
 
  update() {
    this.customerChange.emit(this.customer);
  }
 
}
 
                            
                        

'app-customer-detail' is the name of the selector for this component.

The customer property is the input property decorated with Input.

                              

@Input,() customer:Customer = new Customer();
 
                            
                        

customerChange is decorated as the output property of type EventEmitter

                              

@Output,() customerChange:EventEmitter<Customer> =new EventEmitter<Customer>(); 
                            
                        

Whenever the user updates the customer, we raise the event customerChange. We pass the updated customer as the argument to it.

                              

update() {
  this.customerChange.emit(this.customer);
}
 
                            
                        

The customer-detail.component.html is as follows.

                              

<p>Customer No : {{customer.customerNo}}</p>
<p>Name        : <input [(ngModel)]="customer.name"></p>
<p>Address     : <input [(ngModel)]="customer.address"></p>
<p>city     : <input [(ngModel)]="customer.city"></p>
<p>state     : <input [(ngModel)]="customer.state"></p>
<p>country     : <input [(ngModel)]="customer.country"></p>
 
<button (click)="update()">Update</button>
                            
                        

The ngModel binds the customer to the input element. It is a two-way binding. The click event of the button is bound to update() method in the component.

Parent Component

The job of the parent component is to display a list of customers. When the user clicks on the edit button pass the selected customer to the child component. Then wait for the customerChange event. Update the customer’s list on receipt of data from the child.

The following is the customer-list.component.html

                              
 
<h2>List of Customers</h2>
 
<table class='table'>
  <thead>
    <tr>
      <th>No</th>
      <th>Name</th>
      <th>Address</th>
      <th>City</th>
      <th>State</th>
      <th>Country</th>
      <th>Edit</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let customer of customers;">
      <td>{{customer.customerNo}}</td>
      <td>{{customer.name}}</td>
      <td>{{customer.address}}</td>
      <td>{{customer.city}}</td>
      <td>{{customer.state}}</td>
      <td>{{customer.country}}</td>
      <td><button (click)="showDetails(customer)">Edit</button></td>
    </tr>
  </tbody>
</table>
 
<h3>Details</h3>
<app-customer-detail [customer]="selectedCustomer" (customerChange)="update($event)"></app-customer-detail>
 
                            
                        

Use the ngFor directive to loop through the customer list and display the customer details.

                              
 <tr *ngFor="let customer of customers;">
                            
                        

The event binding to capture the click event. We pass the customer object to the showDetails method

                              
 <td><button (click)="showDetails(customer)">Edit</button></td>
                            
                        

app-customer-detail is the selector for the CustomerDetailComponent. We use the property binding to send the selectedCustomer to the child component. The child component raises the customerChange event, which we listen to using the event binding and call the update method.

app-customer-detail is the selector for the CustomerDetailComponent. We use the property binding to send the selectedCustomer to the child component. The child component raises the customerChange event, which we listen to using the event binding and call the update method.

The component code of the parent component. It has two method showDetails & update

Customer-list.component.ts
                              

import { Component, OnInit } from '@angular/core';
import { Customer } from '../customer';
import { element } from 'protractor';
import { ObjectUnsubscribedError } from 'rxjs';
 
@Component({
  selector: 'app-customer-list',
  templateUrl: './customer-list.component.html',
  styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {
 
  customers: Customer[] = [
 
    {customerNo: 1, name: 'Rahuld Dravid', address: '', city: 'Banglaore', state: 'Karnataka', country: 'India'},
    {customerNo: 2, name: 'Sachin Tendulkar', address: '', city: 'Mumbai', state: 'Maharastra', country: 'India'},
    {customerNo: 3, name: 'Saurrav Ganguly', address: '', city: 'Kolkata', state: 'West Bengal', country: 'India'},
    {customerNo: 4, name: 'Mahendra Singh Dhoni', address: '', city: 'Ranchi', state: 'Bihar', country: 'India'},
    {customerNo: 5, name: 'Virat Kohli', address: '', city: 'Delhi', state: 'Delhi', country: 'India'},
 
  ]
 
  selectedCustomer:Customer = new Customer();
 
  constructor() { }
 
  ngOnInit() {
  }
 
  showDetails(customer:Customer) {
    this.selectedCustomer=Object.assign({},customer)
  }
  
  update(customer:Customer) {
    console.log(customer)
    var cust=this.customers.find(e => e.customerNo==customer.customerNo)
    Object.assign(cust,customer)
    alert("Customer Saved")
  }
}
                            
                        

The showDetails method gets the customer as its argument. We clone it & assign it to selectedCustomer

Since the customer is an object it is Passed by Reference. When you make any modification to the customer it will also be reflected in the customer’s collection. We want the update the customer’s only when we get the data from the child. Hence we clone the customer and send it to the child component.

If you are passing primitive data types like numbers are Passed by Value.

Finally in the root component (i.e. app.component.html) copy the following

                              

<app-customer-list></app-customer-list>
                            
                        

Run the app

image

Notes on @Input & @Output

You can also pass the optional name

Input decorator allows us to pass an option name, which you can use it while binding in the parent

For Example

                              
 
@Input,(‘customerData’) customer:Customer;
                            
                        

Intercept input property changes with a setter

You can also create a setter property

                              

  private _customerData = '';
  @Input()
  set customer(customer: Customer) {
    //You can add some custom logic here
    this._customerData = customer;
    console.log(this._customerData)
  }
  get customer(): string { return this._customerData; }
 
                            
                        

Subscribe to @Input changes using ngChanges

You can also subscribe to the changes using ngOnChanges life cycle hook.

EventEmitters are observable

EventEmitters are RxJs Subjects. Hence you can make use of RxJs operators to manipulate them. Read more about it from this link.

Pass by reference

The objects are passed by reference. Hence if you modify the object, you are updating the original object. The primitive data types like numbers are Passed by Value.

summary

This article shows how to make use of Input, output & EventEmitter in Angular. We use them to communicate with parent & child components. The Child component defines the input & output property using @Input & @output decorators. The Parent sets the input property using property binding. The child component raises the event using EventEmitter whenever it wants to send data to the parent. The parent listens to output property using event binding.